﻿using System;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows.Threading;
using DataStore;
using DataStore.Domain;
using DataStore.Repositories;
using Infrastructure.CurrentData;
using Microsoft.Practices.Composite.Events;

namespace Infrastructure.ViewModels
{
    /// <summary>
    /// AllCompanies viewmodel
    /// </summary>
    public class AllCompaniesViewModel : DataModel
    {
        
        ObservableCollection<CompanyViewModel> _companies = new ObservableCollection<CompanyViewModel>();

        /// <summary>
        /// Initializes a new instance of the <see cref="AllCompaniesViewModel"/> class.
        /// </summary>
        public AllCompaniesViewModel() : base()
        {
            Initialize();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AllCompaniesViewModel"/> class.
        /// </summary>
        /// <param name="eventAggregator">The event aggregator.</param>
        public AllCompaniesViewModel(IEventAggregator eventAggregator) : base(eventAggregator)
        {
            Initialize();
        }

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        void Initialize()
        {
            State = ModelState.Fetching;

            RefreshCompanies();
        }

        /// <summary>
        /// Gets or sets the companies.
        /// </summary>
        /// <value>The companies.</value>
        public ObservableCollection<CompanyViewModel> Companies
        {
            get
            {
                VerifyCalledOnUIThread();
                return _companies;
            }
            set
            {
                VerifyCalledOnUIThread();
                if (_companies != value)
                {
                    _companies = value;
                    OnPropertyChanged("Companies");
                }
            }
        }

        /// <summary>
        /// Refreshes the companies.
        /// </summary>
        void RefreshCompanies()
        {

            if (!ThreadPool.QueueUserWorkItem(FetchCompaniesCallback))
            {
                State = ModelState.Invalid;
            }
        }

        /// <summary>
        /// Fetches the companies callback.
        /// </summary>
        /// <param name="state">The state.</param>
        void FetchCompaniesCallback(object state)
        {
            IDatabase database = Current.Container.Resolve<IDatabase>();
            var unitOfWork = database.CreateUnitOfWork();

            try
            {
                IRepository<Company> repository = new CompanyRepository(unitOfWork);
                var companies = repository.All;

                Dispatcher.BeginInvoke(
                    new ThreadStart(delegate
                                        {
                                            Companies.Clear();
                                            foreach (var company in companies)
                                            {
                                                Companies.Add(new CompanyViewModel(EventAggregator, company));
                                            }

                                            unitOfWork.Dispose();

                                            State = ModelState.Active;
                                            OnLoaded(this, EventArgs.Empty);
                                        }),
                    DispatcherPriority.ApplicationIdle);
            }
            catch (Exception e)
            {
                Log.Error("Failed to load Companies", e);

                unitOfWork.Dispose();
                Dispatcher.BeginInvoke(
                    new ThreadStart(delegate
                                        {
                                            State = ModelState.Invalid;
                                            OnLoaded(this, EventArgs.Empty);
                                        }),
                    DispatcherPriority.ApplicationIdle);

            }
        }
    }
}